import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:talk/pages/device/x_device_router.dart';

import '../../api/DeviceApi.dart';
import '../../api/MessageApi.dart';
import '../../api/UserApi.dart';
import '../../commponets/CustomDatePicker.dart';
import '../../commponets/CustomSwitch.dart';
import '../../commponets/DropDownDevicePicker.dart';
import '../../commponets/ItemView.dart';
import '../../home/AppLocale.dart';
import '../../routers/fluro_navigator.dart';
import '../../tools/widgets/my_app_bar.dart';
import '../../utils/NotificationService.dart';
import '../../utils/toast_utils.dart';
import '../device/model/DeviceAlarm.dart';
import '../provider/CustomBottomPicker.dart';
import 'model/MessageModel.dart';

class MessagePage extends StatefulWidget {
  const MessagePage({
    super.key,
  });

  @override
  State<MessagePage> createState() => _MessagePageState();
}

class _MessagePageState extends State<MessagePage> {
  bool _isLoading = true; // 初始加载状态
  bool _isLoadingMore = false; // 加载更多状态
  bool _hasMoreData = true; // 是否还有更多数据
  int _pageNum = 1; // 当前页码
  final int _pageSize = 10; // 每页条数
  int _totalItems = 0; // 新增：总数据条数，用于判断是否还有更多数据

  final UserApi _userApi = UserApi();
  final MessageApi _messageApi = MessageApi();
  int? userId;
  List<MessageModel> _messageModel = [];
  // 1. 创建通知服务实例
  final NotificationHelper _notificationService = NotificationHelper();

  // 筛选条件状态变量
  int? deviceType; // 设备类型
  int? alarmType; // 报警类型
  DateTime? _startDate; // 开始日期
  DateTime? _endDate; // 结束日期
  String? _messageName;

  // 选中的设备类型和报警类型文本，用于维护勾选状态
  String _selectedDeviceText = "所有设备";
  String _selectedAlarmText = "Quad View";

  // 已读消息ID集合
  final Set<int> _readMessageIds = {};

  // 页面是否活跃的标志
  bool _isActive = true;

  // 列表控制器，用于监听滚动事件
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    // 初始化筛选条件
    deviceType = null;
    alarmType = null;
    _startDate = null;
    _endDate = null;
    _messageName = null;

    // _noti();

    // 监听滚动事件，实现下拉加载更多
    _scrollController.addListener(_scrollListener);

    _fetchData(isLoadMore: false);
  }

  @override
  void dispose() {
    _sendReadMessageIds();
    _isActive = false;
    _scrollController.dispose(); // 释放控制器资源
    super.dispose();
  }



  Future<void> _noti() async {
    await _notificationService.showNotification(
      title: AppLocale.text('m_xinxiaoxi'),
      body: AppLocale.text('m_xinxiaoxidata'),
    );
  }







  // 监听滚动事件，判断是否滚动到了底部
  void _scrollListener() {
    // 优化滚动判断逻辑，避免重复触发
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent - 200 &&
        !_isLoading && !_isLoadingMore && _hasMoreData) {
      _fetchData(isLoadMore: true);
    }
  }

  // 发送已读消息ID到服务器
  Future<void> _sendReadMessageIds() async {
    if (_readMessageIds.isNotEmpty) {
      try {
        // 将集合转换为列表并发送
        final readList = _readMessageIds.toList();
        await _messageApi.getRouters(readList);
        print("已读消息ID已发送: $readList");
      } catch (e) {
        print("发送已读消息ID失败: $e");
      }
    }
  }

  // 获取消息列表，isLoadMore标识是否是加载更多
  Future<void> _fetchData({required bool isLoadMore}) async {
    // 防重复请求
    if (isLoadMore && (_isLoadingMore || !_hasMoreData)) {
      return;
    }

    // 设置加载状态
    setState(() {
      if (isLoadMore) {
        _isLoadingMore = true;
      } else {
        _isLoading = true;
        _messageModel = [];
        _pageNum = 1;
        _hasMoreData = true;
        _totalItems = 0; // 重置总条数
      }
    });

    try {
      if(userId == null ){
        final userData = await _userApi.userData();
        if (userData.code == 200) {
          userId = userData.data['userId'];
        }
      }

      // 格式化日期参数
      String? startDateStr = _startDate != null ? _formatDate(_startDate!) : null;
      String? endDateStr = _endDate != null ? _formatDate(_endDate!) : null;

      // 传递所有筛选参数和分页参数
      final messageData = await _messageApi.messageList(
        userId: userId,
        deviceType: deviceType,
        alarmType: alarmType,
        startDate: startDateStr,
        endDate: endDateStr,
        messageName: _messageName,
        pageNum: _pageNum,
        pageSize: _pageSize,
      );

      if (messageData.code == 200) {
        // 解析数据
        List<MessageModel> newData = (messageData.rows as List<dynamic>)
            .map((item) => MessageModel.fromJson(item))
            .toList();

        // 获取总数据条数（假设接口返回total字段，根据实际接口调整）
        _totalItems = messageData.total ?? 0;

        setState(() {
          // 追加或替换数据
          if (isLoadMore) {
            // 过滤重复数据（根据messageId去重）
            final existingIds = _messageModel.map((m) => m.messageId).toSet();
            newData = newData.where((m) => !existingIds.contains(m.messageId)).toList();
            _messageModel.addAll(newData);
          } else {
            _messageModel = newData;
          }

          // 关键修复：根据总条数判断是否还有更多数据
          _hasMoreData = _messageModel.length < _totalItems;

          // 只有还有更多数据时，才增加页码
          if (_hasMoreData) {
            _pageNum++;
          }

          // 更新加载状态
          _isLoading = false;
          _isLoadingMore = false;
        });
      }
    } catch (e) {
      Toast.show("网络请求错误");
      setState(() {
        _isLoading = false;
        _isLoadingMore = false;
      });
    }
  }


  // 重置筛选条件并重新加载数据
  void _resetFiltersAndLoad() {
    setState(() {
      _pageNum = 1;
      _hasMoreData = true;
      _totalItems = 0; // 重置总条数
    });
    _fetchData(isLoadMore: false);
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        leftTitle: AppLocale.text('d_xiaoxi'),
        leftTitleOffset: 10.0,
        leftTitleVerticalOffset: 4.0,
        showRightButton: true,
        isBack: false,
        leftTitleStyle: const TextStyle(
          fontSize: 18,
          fontWeight: FontWeight.bold,
          color: Colors.black,
        ),

        rightButtonType: RightButtonType.image,
        rightButtonImg: 'images/images/message/t2.png',
        rightButtonImgOffset: 10.0,
        rightButtonImgSize: 24.0,
        onRightButtonPressed: () {
          showModalBottomSheet(
            context: context,
            builder: (BuildContext context) {
              return CustomDatePicker(
                backgroundColor: Colors.white,
                title: "选择日期",
                titleAlignment: Alignment.center,
                maxHeight: 700,
                autoConfirm: true,
                isRange: true,
                onSelected: (startDate, endDate) {
                  setState(() {
                    _startDate = startDate;
                    _endDate = endDate;
                  });
                  _resetFiltersAndLoad();
                },
              );
            },
          );
        },

        //搜索
        showSecondRightButton: true,
        secondRightButtonType: RightButtonType.image,
        secondRightButtonImgOffset: 10.0,
        secondRightButtonImgSize: 24.0,
        secondRightButtonImg: 'images/images/message/t1.png',

        onSecondRightButtonPressed: () {
          showDialog(
            context: context,
            barrierDismissible: true,
            builder: (BuildContext context) {
              return Stack(
                children: [
                  Positioned.fill(
                    child: GestureDetector(
                      onTap: () => Navigator.of(context).pop(),
                      child: Container(color: Colors.black26),
                    ),
                  ),
                  Positioned(
                    top: MediaQuery.of(context).padding.top,
                    left: -20,
                    right: -20,
                    child: Container(
                      margin: EdgeInsets.symmetric(horizontal: 16),
                      child: BrnSearchText(
                        innerPadding: EdgeInsets.only(left: 20, right: 20, top: 10, bottom: 10),
                        maxHeight: 60,
                        innerColor: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(10)),
                        normalBorder: Border.all(color: Color(0xFFF0F0F0), width: 1, style: BorderStyle.solid),
                        activeBorder: Border.all(color: Color(0xFF0984F9), width: 1, style: BorderStyle.solid),
                        onTextClear: () {
                          return false;
                        },
                        autoFocus: true,
                        action: Container(),
                        onActionTap: () {
                          Navigator.of(context).pop();
                          BrnToast.show('取消', context);
                        },
                        onTextCommit: (text) {
                          Navigator.of(context).pop();
                          _messageName = text;
                          _resetFiltersAndLoad();
                        },
                        onTextChange: (text) {
                          // 处理文本变化
                        },
                      ),
                    ),
                  ),
                ],
              );
            },
          );
        },
      ),

      body: Container(
        child: _isLoading
            ? const Center(child: CircularProgressIndicator())
            : ListView(
          controller: _scrollController,
          padding: const EdgeInsets.all(0.0),
          children: [
            const SizedBox(height: 20,),

            // 设备类型和报警类型筛选下拉框
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                DropDownDevicePicker(
                  title: _selectedDeviceText,
                  titleStyle: const TextStyle(
                    fontSize: 14.0,
                    color: Colors.black,
                  ),
                  arrowIcon: const Icon(
                    Icons.arrow_drop_down,
                    size: 20,
                    color: Colors.black87,
                  ),
                  deviceList: const [
                    '所有设备',
                    '智能摄像头',
                    '智能门铃',
                    '智能室内机',
                    '智能门禁机',
                  ],
                  itemStyle: const TextStyle(
                    fontSize: 14.0,
                    color: Color(0xFF595959),
                    fontWeight: FontWeight.bold,
                  ),
                  dropdownBackgroundColor: Colors.white,
                  mainContainerColor: Colors.transparent,
                  borderColor: Colors.transparent,
                  checkIcon: const Icon(
                    Icons.check,
                    color: Colors.black38,
                  ),
                  width: 140,
                  height: 50,
                  alignment: DropDownMainAxisAlignment.spaceEvenly,
                  dropdownWidth: 130,
                  maxDropdownHeight: 245,
                  trianglePosition: 85,
                  itemPadding: EdgeInsets.only(left: 2.0),
                  onSelected: (device) {
                    print("设备类型选中了: $device");
                    setState(() {
                      _selectedDeviceText = device;
                    });

                    switch(device) {
                      case '智能摄像头':
                        deviceType = 1;
                        break;
                      case '智能门铃':
                        deviceType = 2;
                        break;
                      case '智能室内机':
                        deviceType = 3;
                        break;
                      case '智能门禁机':
                        deviceType = 4;
                        break;
                      default:
                        deviceType = null;
                    }
                    _resetFiltersAndLoad();
                  },
                  isSelected: (device) => device == _selectedDeviceText,
                ),

                const SizedBox(width: 30,),

                // 报警类型筛选下拉框
                DropDownDevicePicker(
                  title: _selectedAlarmText,
                  titleStyle: const TextStyle(
                    fontSize: 14.0,
                    color: Colors.black,
                  ),
                  arrowIcon: const Icon(
                    Icons.sync_alt,
                    size: 20,
                    color: Colors.black87,
                  ),
                  deviceList: const [
                    'Quad View',
                    'CAM1',
                    'CAM2',
                    'CAM3',
                    'CAM4',
                  ],
                  itemStyle: const TextStyle(
                    fontSize: 14.0,
                    color: Color(0xFF595959),
                    fontWeight: FontWeight.bold,
                  ),
                  dropdownBackgroundColor: Colors.white,
                  mainContainerColor: Colors.transparent,
                  borderColor: Colors.transparent,
                  checkIcon: const Icon(
                    Icons.check,
                    color: Colors.black38,
                  ),
                  width: 140,
                  height: 50,
                  alignment: DropDownMainAxisAlignment.spaceEvenly,
                  dropdownWidth: 130,
                  maxDropdownHeight: 245,
                  trianglePosition: 85,
                  itemPadding: EdgeInsets.only(left: 2.0),
                  onSelected: (device) {
                    print("报警类型选中了: $device");
                    setState(() {
                      _selectedAlarmText = device;
                    });

                    switch(device) {
                      case 'CAM1':
                        alarmType = 1;
                        break;
                      case 'CAM2':
                        alarmType = 2;
                        break;
                      case 'CAM3':
                        alarmType = 3;
                        break;
                      case 'CAM4':
                        alarmType = 4;
                        break;
                      default:
                        alarmType = null;
                    }
                    _resetFiltersAndLoad();
                  },
                  isSelected: (device) => device == _selectedAlarmText,
                ),
              ],
            ),

            const SizedBox(height: 10),

            // 消息列表
            ..._messageModel.map((message) {
              return Column(
                  children: [
                    ItemView(
                      width: double.infinity,
                      height: 70,
                      leftWidget: Row(
                        children: [
                          Image.asset(
                            getMessageImage(message.alarmType),
                            width: 40,
                            height: 40,
                            fit: BoxFit.contain,
                          ),
                          const SizedBox(width: 10),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const SizedBox(height: 12),
                              Text(
                                message.messageName ?? '未知',
                                style: const TextStyle(
                                  fontSize: 14.0,
                                  color: Colors.black,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              const SizedBox(height: 5),
                              Container(
                                width: 200,
                                child: Text(
                                  message.messageContent ?? '未知',
                                  style: const TextStyle(
                                    fontSize: 12.0,
                                    color: Colors.black45,
                                  ),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                  softWrap: false,
                                ),

                              )
                            ],
                          ),
                        ],
                      ),
                      rightWidget: Column(
                        children: [
                          const SizedBox(height: 12),
                          Text(
                            message.createTimeData ?? '',
                            style: const TextStyle(
                              fontSize: 12.0,
                              color: Colors.black45,
                            ),
                          ),
                          const SizedBox(height: 8),
                          if (message.isRead != 1 && !_readMessageIds.contains(message.messageId))
                            Container(
                              width: 6,
                              height: 6,
                              decoration: const BoxDecoration(
                                shape: BoxShape.circle,
                                color: Colors.red,
                              ),
                            ),
                        ],
                      ),
                      borderRadius: 8,
                      onTap: () {
                        _handleMessageTap(message);
                      },
                    ),
                    const SizedBox(height: 12,),
                  ]
              );
            }).toList(),

            // 加载更多指示器
            if (_isLoadingMore)
              const Padding(
                padding: EdgeInsets.symmetric(vertical: 16),
                child: Center(
                  child: CircularProgressIndicator(),
                ),
              ),

            // 没有更多数据时显示
            if (!_hasMoreData && _messageModel.isNotEmpty)
              const Padding(
                padding: EdgeInsets.symmetric(vertical: 16),
                child: Center(
                  child: Text(
                    "没有更多数据了",
                    style: TextStyle(color: Colors.grey),
                  ),
                ),
              ),

            const SizedBox(height: 10),
          ],
        ),
      ),
    );
  }

  String getMessageImage(int? alarmType) {
    switch (alarmType) {
      case 1:
        return "images/images/message/m1.png";
      case 2:
        return "images/images/message/m2.png";
      case 3:
        return "images/images/message/m3.png";
      case 4:
        return "images/images/message/m4.png";
      default:
        return "images/images/message/m1.png";
    }
  }

  // 处理消息点击事件
  void _handleMessageTap(MessageModel message) {
    if (_isActive && message.isRead != 1 && message.messageId != null) {
      setState(() {
        _readMessageIds.add(message.messageId!);
      });
    }
  }

  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }
}
